package respository

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/dto"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/vo"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type ISceneRepository interface {
	Create(scene model.Scene)
	Update(scene model.Scene)
	SelectById(Id int)
	SelectFullSceneById(Id int)
	DeleteById(Id int)
	List(sceneList vo.SceneList)
}

type SceneRepository struct {
	DB *gorm.DB
}

func (s SceneRepository) Create(scene model.Scene) (int, error){

	if err := s.DB.Create(&scene).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return 0, err
	}

	return scene.ID, nil
}

func (s SceneRepository) Update(scene model.Scene) (*model.Scene, error){

	if err := s.DB.Updates(&scene).Error;err != nil {
		return nil, err
	}

	return &scene,nil
}

func (s SceneRepository) SelectById(Id int) (scene *model.Scene,err error){

	if err := s.DB.Where("id = ?",Id).First(&scene).Error; err != nil{
		return nil, err
	}

	return
}

func (s SceneRepository) SelectFullSceneById(Id int) *dto.FullSceneDto {

	s.DB = s.DB.Where("scenes.id = ?", Id)
	selectSql := "scenes.id,scenes.name,scenes.scene_id as scene_id," +
		"s.name as scene_name,scenes.type,scenes.desc,scenes.created_at,scenes.updated_at"
	joinsSql := "left join scenes as s on scenes.scene_id = s.id"

	var fullScene dto.FullSceneDto

	s.DB.Model(&model.Scene{}).Select(selectSql).Joins(joinsSql).
		Order("scenes.created_at desc").Scan(&fullScene)

	return &fullScene
}

func (s SceneRepository) DeleteById(Id int) (rowsAffected int64) {

	rowsAffected = s.DB.Where("id = ?", Id).Delete(model.Scene{}).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return
}

func (s SceneRepository) List(sceneList vo.SceneList) (scenes []dto.FullSceneDto, total int64){

	// 条件查询
	if sceneList.ID > 0  {
		s.DB = s.DB.Where("scenes.id = ?", sceneList.SceneId)
	}
	if sceneList.SceneId > 0  {
		s.DB = s.DB.Where("scenes.scene_id = ?", sceneList.SceneId)
	}
	if sceneList.Name != ""  {
		s.DB = s.DB.Where("scenes.name like ?", "%" + sceneList.Name + "%")
	}
	if sceneList.Type !="" {
		s.DB = s.DB.Where("scenes.type = ?", sceneList.Type)
	}
	if sceneList.PageNum == 0  {
		sceneList.PageNum = 1
	}
	if sceneList.PageSize == 0  {
		sceneList.PageSize = 10
	}

	selectSql := "scenes.id,scenes.name,scenes.scene_id as scene_id," +
		"s.name as scene_name,scenes.type,scenes.desc,scenes.created_at,scenes.updated_at"
	joinsSql := "left join scenes as s on scenes.scene_id = s.id"

	//总记录数
	s.DB.Model(&model.Scene{}).Count(&total)

	s.DB.Model(&model.Scene{}).Select(selectSql).
		Joins(joinsSql).
		Order("scenes.created_at desc").
		Offset((sceneList.PageNum -1) * sceneList.PageSize).
		Limit(sceneList.PageSize).Scan(&scenes)

	return
}

func NewSceneRepository() SceneRepository{
	db := common.GetDB()
	//db.AutoMigrate(model.Scene{})

	return SceneRepository{DB: db}
}